package fcache

import (
	"io"
	"os"
	"path/filepath"

	"gitee.com/linxing_3/sr-core/utils/crypto"
)

type Cache struct {
	rootDir    string
	previewDir string
	thumbDir   string
}

func NewCache(cachedir, thumbdir, previewdir string) *Cache {
	return &Cache{
		rootDir:    cachedir,
		previewDir: previewdir,
		thumbDir:   thumbdir,
	}
}

func (s *Cache) SaveThumb(data io.Reader) (string, error) {
	relativePath, err := s.getRelativeHashPath(data)
	if err != nil {
		return "", err
	}

	thumbPath := filepath.Join(s.rootDir, s.thumbDir, relativePath)

	if err = s.writeToFile(thumbPath, data); err != nil {
		return "", err
	}

	return thumbPath, err
}

func (s *Cache) SavePreview(data io.Reader) (string, error) {
	relativePath, err := s.getRelativeHashPath(data)
	if err != nil {
		return "", err
	}
	previewPath := filepath.Join(s.rootDir, s.previewDir, relativePath)
	if err = s.writeToFile(previewPath, data); err != nil {
		return "", err
	}
	return previewPath, err
}

func (s *Cache) writeToFile(path string, data io.Reader) error {
	if stat, err := os.Stat(path); err == nil && !stat.IsDir() {
		// 文件存在
		return os.ErrExist
	}

	f, err := os.Create(path)
	if err != nil {
		return err
	}

	_, err = io.Copy(f, data)
	if err != nil {
		return err
	}
	return nil
}

func (s *Cache) getRelativeHashPath(data io.Reader) (string, error) {
	dataHash, err := crypto.Hash256Buf(data)
	if err != nil {
		return "", err
	}
	return filepath.Join(dataHash[:2], dataHash), nil
}
